import { pickStateManager, widgetManager } from '@/common/managers';
import { i18n } from '@/common/utils';
import { IChangeEvent } from '@rjsf/core';
import { CmdDialogForm, KEYBOARD_KEY } from 'nextcae-base';
import { useEffect, useState } from 'react';
import { schema, uiSchema } from './data';
import { NMMeshBaseCommand, TopoDialogProps } from '@/common/types';
import { mesh } from '@/domain';
import Base from '@/common/cmdBase/cmdBase';
import { PartMaterialField } from '@/components/PartMaterial';
// 面网格
function Command({ title, onClose, icon }: TopoDialogProps) {
  const [hintMessage] = useState('进入网格映射命令，请选择面网格');
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState<any>({
    Settings: { dir: 'default' },
    Selection: { source: [], target: [] },
  });
  useEffect(() => {
    window.addEventListener('keyup', onKeyUp);
    return () => {
      window.removeEventListener('keyup', onKeyUp);
    };
  }, []);

  const onKeyUp = (e: KeyboardEvent) => {
    // 点击键盘ESC退出命令
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };

  useEffect(() => {
    widgetManager.hint(hintMessage);
    return () => {
      widgetManager.hint();
    };
  }, [hintMessage]);

  const handleResultSelectChange = (data: IChangeEvent, id: string) => {
    if (!id) return;
    const keys = id.split('_');
    setFormData((state) => {
      return {
        ...state,
        [keys[1]]: { ...state[keys[1]], ...data.formData[keys[1]] },
      };
    });
  };
  const commend = async () => {
    const params = {
      Source: formData.Selection.source.map((it) => {
        return it.type === 'feature' ? it.dxid : Base.makeIdNew(it);
      })[0],
      Target: formData.Selection.target.map((it) =>
        it.type === 'feature' ? it.dxid : Base.makeIdNew(it),
      )[0],
      Property: formData.AddTo.property,
      Part: formData.AddTo.part,
    };
    try {
      setIsLoading(true);
      await mesh.projection(params);
      setFormData((state) => ({
        ...state,
        Selection: { source: [], target: [] },
      }));
      setTimeout(() => pickStateManager.reset(), 800);
    } finally {
      setIsLoading(false);
    }
  };
  const isFormDataValid = () => {
    return (
      formData.Selection.source.length > 0 &&
      formData.Selection.target.length > 0
    );
  };

  return (
    <CmdDialogForm
      title={title}
      formData={formData}
      titleIcon={icon}
      submitLoading={isLoading}
      onSubmit={() => commend()}
      onChange={handleResultSelectChange}
      schema={schema}
      extraUiSchema={uiSchema}
      isFormDataValid={isFormDataValid()}
      fields={{
        partMaterialField: PartMaterialField,
      }}
      onClose={onClose}></CmdDialogForm>
  );
}
export const cmdMeshPro: NMMeshBaseCommand = {
  id: 'cmdMeshPro',
  icon: 'commands/mesh/mesh-projection',
  label: 'command.mesh.meshProjection',
  create: (label: string, onClose: () => void) => (
    <Command
      title={i18n.t(label)}
      onClose={onClose}
      icon={cmdMeshPro.icon}
    />
  ),
};
